<script lang="ts">
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import { SimpleAnswer, SimpleQuestion } from '$lib/api/proto/resource_exam_type_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { roadmapStore } from '../../store.svelte';

	interface Props {
		questionId: string;
		question: Any;
		answer: Any;
	}
	let props: Props = $props();

	const question = $derived(Any.unpack(props.question, SimpleQuestion));

	let answer = $state(
		props.answer.typeUrl.endsWith('.SimpleAnswer')
			? Any.unpack(props.answer, SimpleAnswer).answer
			: ''
	);

	async function setAnswer() {
		if (userStore.userSession == null || roadmapStore.selectNodeIdList.length == 0) {
			return;
		}
		await callApi(
			appStore.resourceExamApiClient.setStateByRoadmap({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				nodeId: roadmapStore.selectNodeIdList[0],
				questionId: props.questionId,
				answer: Any.pack(
					{
						answer: answer
					},
					SimpleAnswer
				)
			}).response
		);
		roadmapStore.resourceStateVersion += 1;
	}

	$effect(() => {
		answer = props.answer.typeUrl.endsWith('.SimpleAnswer')
			? Any.unpack(props.answer, SimpleAnswer).answer
			: '';
	});
</script>

<div class="prose max-w-none p-2 w-full">
	<h3>问题:{question.question}</h3>
	<h4>回答</h4>
	{#if roadmapStore.roadmapMode == 'update'}
		<textarea class="textarea w-full" bind:value={answer} rows="5"></textarea>
		<div class="flex justify-end mr-[20px] mt-[10px]">
			<button
				type="button"
				class="btn btn-accent"
				onclick={() => setAnswer()}
				disabled={answer.trim() == ''}>保存</button
			>
		</div>
	{:else if roadmapStore.roadmapMode == 'view'}
		<pre class="bg-base-100 text-primary w-full">{answer}</pre>
	{/if}
	{#if roadmapStore.roadmapMode == 'view'}
		<h4>参考答案:</h4>
		<pre class="bg-base-100 text-primary w-full">{question.sampleAnswer}</pre>
	{/if}
</div>
